<template>
  <el-dialog
    v-el-drag-dialog
    :title="!dataForm.activityId ? '新增活动' : '修改活动'"
    :close-on-click-modal="false"
    :visible.sync="visible">
    <el-form :model="dataForm" :rules="dataRule" ref="dataForm" @keyup.enter.native="dataFormSubmit()" label-width="80px">
    <el-form-item label="活动标题" prop="activityTitle">
      <el-input v-model="dataForm.activityTitle" placeholder="活动标题会在用户端页面展示,活动标题6个字符内" maxlength="6"></el-input>
    </el-form-item>
    <el-form-item label="跳转地址" prop="activityUrl" v-if="!dataForm.activityId">
      <el-select v-model="dataForm.activityUrl" placeholder="跳转地址" style="width: 350px">
        <el-option
          v-for="item in this.activityClassUrl"
          :key="item.id"
          :label="item.outerTitle"
          :value="item.id">
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="开始时间" prop="time">
      <el-date-picker
        :editable="false"
        v-model="dataForm.time"
        type="daterange"
        value-format = "yyyy-MM-dd HH:mm:ss"
        range-separator="-"
        start-placeholder="活动开始时间"
        end-placeholder="活动结束时间">
      </el-date-picker>
    </el-form-item>
    <el-form-item label="图标" prop="activityImages">
      <el-upload
        class="avatar-uploader"
        :action="this.$http.adornUrl(`/banner/uploadBanner?token=${this.$cookie.get('token')}`)"
        :show-file-list="false"
        :on-success="handleAvatarSuccess"
        :before-upload="beforeAvatarUpload">
        <img v-if="dataForm.activityImages" :src="dataForm.activityImages" class="avatar">
        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
      </el-upload>
    </el-form-item>
    <el-form-item label="限购" prop="restrictions">
      <el-radio v-model="dataForm.restrictions" label = '1'>开启</el-radio>
      <el-radio v-model="dataForm.restrictions" label = '0'>关闭</el-radio>
    </el-form-item>
    <el-form-item label="抢购模板" prop="templateId" v-if="!dataForm.activityId">
      <el-select v-model="dataForm.templateId" placeholder="请选择抢购模板">
        <el-option
          v-for="item in this.dataList"
          :key="item.id"
          :label="item.title"
          :value="item.id">
        </el-option>
      </el-select>
    </el-form-item>
    <el-form-item label="备注" prop="publishRemark">
      <el-input v-model="dataForm.publishRemark" placeholder="备注"></el-input>
    </el-form-item>
    <el-form-item label="活动区域" prop="" v-if="!dataForm.activityId">
      <div class="abk-select-city" @click.stop="showCitysHandler">
    <el-input
      @input="inputChangeHandler"
      v-model="searchText"
      class="abk-select-input"
      :placeholder="placeholderText">
      <i slot="suffix" v-if="!showCitys" class="el-input__icon el-icon-caret-bottom"></i>
      <i slot="suffix" v-else @click.stop="hideCitysHandler" class="el-input__icon el-icon-caret-top"></i>
    </el-input>

    <div class="dropdown-box" v-show="showCitys">
      <div class="city-tree-box" v-show="showTrees">
        <el-tree
          :data="cityInfos"
          ref="selectCityTree"
          show-checkbox
          @check-change="treeChangeHandler"
          node-key="value">
        </el-tree>
      </div>

      <div class="city-search-box" v-show="!showTrees">
        <el-checkbox-group v-model="checkCitiesList">
          <el-checkbox class="checkbox-item" v-for="city in searchResultsList"
            :label="city.regionId"
            :key="city.regionId"
            @change="value => searchItemHandler(city, value)">
              <span v-if="city.level === 2">{{getCityNameByRegionId(city.upRegionId)}}</span> <span>{{city.name}}</span>
            </el-checkbox>
        </el-checkbox-group>
        <!-- <ul>
          <li v-for="item in searchResultsList" @click="searchItemHandler(item)">{{item.name}}</li>
        </ul> -->
      </div>
    </div>


  </div>
    </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="visible = false">取消</el-button>
      <el-button type="primary" @click="dataFormSubmit()">确定</el-button>
    </span>
  </el-dialog>
</template>

<script>
  // import _ from 'lodash'
  import {cityLists} from '@/utils/cityList'
  let cityMap = {}
  export default {
    props: ['placeholder', 'checkcitylist'],
    data () {
      return {
        visible: false,
        dataList: [],
        infos: [],
        citys: [],
        showTrees: true,
        showCitys: false,
        searchText: '',
        checkCitiesList: [],
        activityClassUrl: [],
        searchResultsList: [],
        placeholderText: this.placeholder || '请添加地区',
        data1: null,
        dataForm: {
          templateId: 0,
          activityTitle: '',
          publishRemark: '',
          time: new Date(),
          activityImages: '',
          activityId: 0,
          activityNo: '',
          activityUrl: '',
          restrictions: '1'
        },
        dataRule: {
          activityTitle: [
            { required: true, message: '活动标题不能为空', trigger: 'blur' }
          ],
          time: [
            { required: true, message: '时间不能为空', trigger: 'blur' }
          ]
        }
      }
    },
    model: {
      prop: 'checkcitylist',
      event: 'change'
    },
    mounted () {
      this.treeChangeHandler()
    },
    watch: {
      citys (n, o) {
        this.placeholderText = '请添加地区'
      }
    },
    computed: {
      cityInfos () {
        let infos = []
        this.citys = cityLists
        let province = this.citys.filter(o => {
          cityMap[o.regionId] = o.label
          return o.level === 1
        })
        province.map(p => {
          p.children = []
          this.citys.map(o => {
            if (o.level === 2) {
              if (o.value.substr(0, 2) === p.value.substr(0, 2)) {
                p.children.push(o)
              }
            }
          })
        })
        infos = [
          {
            label: '全国',
            value: '000000',
            level: 0,
            children: province
          }
        ]
        return infos
      },
      checkedTreeNodes () {
        let list = this.$refs.selectCityTree.getCheckedNodes()
        return list
      }
    },
    methods: {
      handleAvatarSuccess (res, file) {
        this.dataForm.activityImages = res.data
      },
      beforeAvatarUpload (file) {
        console.log(file)
        const isJPG = file.type === 'image/jpeg' || 'image/png' || 'image/gif'
        // const isLt2M = file.size / 1024 / 1024 < 2;

        if (!isJPG) {
          this.$message.error('上传图片只能是 JPG、PNG、GIF 格式!')
        }
        // if (!isLt2M) {
        //   this.$message.error('上传头像图片大小不能超过 2MB!');
        // }
        // return isJPG && isLt2M;
        return isJPG
      },
      init (id) {
        this.infos = []
        this.citys = []
        this.searchText = ''
        this.checkCitiesList = []
        this.searchResultsList = []
        this.dataForm.activityTitle = ''
        this.dataForm.publishRemark = ''
        this.dataForm.activityImages = ''
        this.dataList = []
        this.dataForm.time = null
        this.dataForm.templateId = null
        this.dataForm.activityId = id
        this.dataList.restrictions = '1'
        this.visible = true
        this.$http({
          url: this.$http.adornUrl('/activity/spike/queryActivityTemplateList'),
          method: 'get',
          params: this.$http.adornParams({
            'page': 1,
            'limit': 100
          })
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.dataList = data.data.list
          }
        })
        // 活动地址分类
        this.$http({
          url: this.$http.adornUrl('/outer/queryActivityOuterChainList'),
          method: 'get',
          params: this.$http.adornParams()
        }).then(({data}) => {
          if (data && data.code === 0) {
            this.activityClassUrl = data.data
          }
        })
        this.$nextTick(() => {
          this.$refs['dataForm'].resetFields()
          if (this.dataForm.activityId) {
            this.$http({
              url: this.$http.adornUrl(`/activity/spike/getActivityById/${this.dataForm.activityId}`),
              method: 'get',
              params: this.$http.adornParams()
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.dataForm.activityNo = data.data.activityNo
                this.dataForm.activityTitle = data.data.activityTitle
                this.dataForm.publishRemark = data.data.publishRemark
                this.dataForm.time = [data.data.beginTime, data.data.endTime]
                if (data.data.activityImages != null && data.data.activityImages !== '') {
                  this.dataForm.activityImages = 'https://image.yilianbaihui.cn/consumer/' + data.data.activityImages
                }
                this.dataForm.activityUrl = data.data.activityUrl
                this.dataForm.restrictions = data.data.restrictions + ''
              }
            })
          }
        })
      },
      // 表单提交
      dataFormSubmit () {
        if (this.dataForm.activityImages !== '') {
          let index = this.dataForm.activityImages.lastIndexOf('\/')
          this.dataForm.activityImages  = this.dataForm.activityImages.substring(index + 1, this.dataForm.activityImages.length)
          this.dataForm.activityImages = 'banner/' + this.dataForm.activityImages
        }
        this.$refs['dataForm'].validate((valid) => {
          if (valid && !this.dataForm.activityId) {
            if (this.dataForm.templateId === null) {
              this.$message.error('必须选择活动模板！')
              return
            }
            let addressList = this.placeholderText.split(',')
            if (addressList.length <= 0) {
              this.$message.error('未选择活动区域！')
            }
            if (this.placeholderText === '请添加地区') {
              this.$message.error('请添加活动的区域！')
              return
            }
            if (this.dataForm.activityUrl === '') {
              this.$message.error('请选择活动外链')
              return
            }
            this.$http({
              url: this.$http.adornUrl(`/activity/spike/add/${this.placeholderText}`),
              method: 'post',
              data: this.$http.adornData({
                'activityId': this.dataForm.activityId || undefined,
                'activityTitle': this.dataForm.activityTitle,
                'beginTime': this.dataForm.time[0],
                'endTime': this.dataForm.time[1],
                'publishRemark': this.dataForm.publishRemark,
                'atId': this.dataForm.templateId,
                'activityImages': this.dataForm.activityImages,
                'activityUrl': this.dataForm.activityUrl,
                'restrictions': this.dataForm.restrictions
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          } else if (valid && this.dataForm.activityId) {
            this.$http({
              url: this.$http.adornUrl(`/activity/spike/modify`),
              method: 'post',
              data: this.$http.adornData({
                'activityId': this.dataForm.activityId || undefined,
                'activityTitle': this.dataForm.activityTitle,
                'beginTime': this.dataForm.time[0],
                'endTime': this.dataForm.time[1],
                'publishRemark': this.dataForm.publishRemark,
                'activityImages': this.dataForm.activityImages,
                'restrictions': this.dataForm.restrictions
              })
            }).then(({data}) => {
              if (data && data.code === 0) {
                this.$message({
                  message: '操作成功',
                  type: 'success',
                  duration: 1500,
                  onClose: () => {
                    this.visible = false
                    this.$emit('refreshDataList')
                  }
                })
              } else {
                this.$message.error(data.msg)
              }
            })
          }
        })
      },
      setChecked () {
        this.$nextTick(() => {
          this.$refs.selectCityTree.setCheckedKeys(this.checkcitylist)
          this.treeChangeHandler()
        })
      },
      hideSelectCityHandler () {
        this.hideCitysHandler()
        this.showTrees = true
        this.searchText = ''
      },
      getCheckedList () {
        return this.checkedTreeNodes
      },
      getCityNameByRegionId (id) {
        return cityMap[id]
      },
      showCitysHandler () {
        this.showCitys = true
        document.removeEventListener('click', this.hideSelectCityHandler)
        document.addEventListener('click', this.hideSelectCityHandler, false)
      },
      hideCitysHandler () {
        this.showCitys = false
        this.$emit('blur')
        document.removeEventListener('click', this.hideSelectCityHandler)
      },
      inputChangeHandler () {
        let serchkey = this.searchText.toUpperCase()
        let citys = this.citys
        if (serchkey === '') {
          this.searchResultsList = []
        } else {
          this.searchResultsList = citys
          .filter(o => {
            return o.level === 1 || o.level === 2
          })
          .filter(o => {
            o.shortSpell = o.shortSpell || ''
            o.spell = o.spell || ''
            o.fullName = o.fullName || ''
            return o.shortSpell.toUpperCase().indexOf(serchkey) === 0 || o.spell.toUpperCase().indexOf(serchkey) === 0 || o.fullName.indexOf(serchkey) === 0
          })
        }
        this.showTrees = this.searchResultsList.length === 0
      },
      searchItemHandler (city, value) {
        this.$refs.selectCityTree.setChecked(city.regionId, value, true)
      },
      treeChangeHandler () {
        debugger
        if (!this.checkcitylist) {
          this.$emit('change', this.getCheckedList())
        }
        if (this.getCheckedList()[0] && this.getCheckedList()[0].value === '000000') {
          this.placeholderText = '全国地区'
        } else {
          this.placeholderText = this.getCheckedList().filter(o => o.level === 2 || o.level === 0).map(o => o.label).join(',') || this.placeholder || '请添加地区'
          if (this.placeholderText === '请添加地区') {
            this.$message.error('请添加活动的区域！')
            return
          }
        }
      }
    }
  }
</script>
<style>
  .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409EFF;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 128px;
    height: 128px;
    line-height: 128px;
    text-align: center;
  }
  .avatar {
    width: 128px;
    height: 128px;
    display: block;
  }
</style>
